package com.baiyimi.powerjob.worker;

import com.baiyimi.powerjob.common.utils.NetUtils;
import com.baiyimi.powerjob.worker.background.OmsLogHandler;
import com.baiyimi.powerjob.worker.background.WorkerHealthReporter;
import com.baiyimi.powerjob.worker.common.WorkerRuntime;
import com.google.common.base.Stopwatch;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

@Slf4j
public class PowerJobWorker implements ApplicationContextAware, InitializingBean, DisposableBean {

    private ScheduledExecutorService timingPool;

    private final WorkerRuntime workerRuntime = new WorkerRuntime();

    private final AtomicBoolean initialized = new AtomicBoolean();


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {

    }

    @Override
    public void afterPropertiesSet() throws Exception {
        init();
    }

    public void init() {

        Stopwatch stopwatch = Stopwatch.createStarted();

        //初始化元数据
        String workerAddress = NetUtils.getLocalHost();

        // 初始化定时线程池
        ThreadFactory timingPoolFactory = new ThreadFactoryBuilder().setNameFormat("oms-worker-timing-pool-%d").build();
        timingPool = Executors.newScheduledThreadPool(3, timingPoolFactory);

        // 初始化日志系统
        OmsLogHandler omsLogHandler = new OmsLogHandler();


        // 初始化定时任务
        timingPool.scheduleAtFixedRate(new WorkerHealthReporter(workerRuntime), 0, 15, TimeUnit.SECONDS);
        timingPool.scheduleWithFixedDelay(omsLogHandler.logSubmitter, 0, 5, TimeUnit.SECONDS);

    }


    @Override
    public void destroy() throws Exception {
        log.info("[destroy]");
    }
}
